package com.dcsgo.socketPlay.client.game;

import com.dcsgo.socketPlay.client.Services;
import com.dcsgo.socketPlay.common.Ball;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;

/**
 * @author DCSGO
 * @version 1.0
 * 游戏绘图面板
 */
public class GamePanel extends JPanel implements Runnable, KeyListener {
    private static final int panelWidth;
    private static final int panelHeight;
    private static final int ballSize;
    private static Ball replaceBall;
    private static List<Ball> balls;
    private static boolean loop = true;


    @Override
    public void run() {
        while (loop) {
            repaint();
        }

    }

    public static void shutdown() {
        balls.clear();
        loop = false;
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        //绘制游戏区
        g.setColor(Color.black);
        g.fillRect(0, 0, panelWidth, panelHeight);
        //绘制所有小球
        drawBalls(balls, g);
    }

    private void drawBalls(List<Ball> balls, Graphics g) {
        g.setColor(Color.green);
        for (Ball ball : balls) {
            if (ball.isVisible()) {
                g.fillOval(ball.getX(), ball.getY(), ballSize, ballSize);
            }
        }
    }

    public GamePanel() {
        repaint();
    }

    static {
        panelWidth = Integer.parseInt(Game.getProperty("gamePanelWidth"));
        panelHeight = Integer.parseInt(Game.getProperty("gamePanelHeight"));
        ballSize = Integer.parseInt(Game.getProperty("ballSize"));
    }

    public static void setReplaceBall(Ball replaceBall) {
        GamePanel.replaceBall = replaceBall;
    }

    public static void setBalls(List<Ball> balls) {
        GamePanel.balls = balls;
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    //相应键盘操作
    @Override
    public void keyPressed(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_W) {//向上
            replaceBall.moveUp();
            //向服务端发送 PLAYER_OPERATION消息
            Services.sendPlayerOperation(replaceBall);

        } else if (e.getKeyCode() == KeyEvent.VK_D) {
            replaceBall.moveRight();
            Services.sendPlayerOperation(replaceBall);

        } else if (e.getKeyCode() == KeyEvent.VK_S) {
            replaceBall.moveDown();
            Services.sendPlayerOperation(replaceBall);

        } else if (e.getKeyCode() == KeyEvent.VK_A) {
            replaceBall.moveLeft();
            Services.sendPlayerOperation(replaceBall);
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }
}
